package org.onion.pattern.notify.dingtalk.impl;


import com.dingtalk.api.request.OapiRobotSendRequest;
import lombok.Setter;
import org.onion.pattern.notify.dingtalk.DingTalkRobotNotifier;
import org.onion.pattern.notify.dingtalk.DingTalkRobotNotifyExecutor;
import org.onion.pattern.notify.dingtalk.msg.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Setter
public class DingTalkRobotNotifierImpl implements DingTalkRobotNotifier {
    private static final String MSG_TYPE_TEXT = "text";
    private static final String MSG_TYPE_LINK = "link";
    private static final String MSG_TYPE_MARKDOWN = "markdown";
    private static final String MSG_TYPE_ACTION_CARD = "actionCard";
    private static final String MSG_TYPE_FEED_CARD = "feedCard";

    private final String accessToken;
    private String signKey;
    private final DingTalkRobotNotifyExecutor executor;

    public DingTalkRobotNotifierImpl(String accessToken) {
        this(accessToken, DingTalkRobotNotifyExecutor.EXECUTOR);
    }

    public DingTalkRobotNotifierImpl(String accessToken, DingTalkRobotNotifyExecutor executor) {
        this.accessToken = Objects.requireNonNull(accessToken);
        this.executor = Objects.requireNonNull(executor);
    }

    public DingTalkRobotNotifierImpl setSignKey(String signKey) {
        this.signKey = signKey;
        return this;
    }

    @Override
    public void sendMsg(String content) {
        this.sendMsg(content, null);
    }

    @Override
    public void sendMsg(String content, MsgAt at) {
        //参数	参数类型	必须	说明
        //msgtype	String	是	消息类型，此时固定为：text
        //content	String	是	消息内容
        //atMobiles	Array	否	被@人的手机号(在content里添加@人的手机号)
        //isAtAll	bool	否	@所有人时：true，否则为：false

        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
        text.setContent(content);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(MSG_TYPE_TEXT);
        request.setText(text);
        request.setAt(toAt(at));

        DingTalkRobotNotifyExecutor.Msg msg = new DingTalkRobotNotifyExecutor.Msg();
        msg.setAccessToken(accessToken);
        msg.setSignKey(signKey);
        msg.setRequest(request);
        this.executor.write(msg);
    }

    @Override
    public void sendMsg(DingTalkRobotLinkMsg msg) {
        this.sendMsg(msg, null);
    }

    @Override
    public void sendMsg(DingTalkRobotLinkMsg msg, MsgAt at) {
        //参数	参数类型	必须	说明
        //msgtype	String	是	消息类型，此时固定为：link
        //title	String	是	消息标题
        //text	String	是	消息内容。如果太长只会部分展示
        //messageUrl	String	是	点击消息跳转的URL
        //picUrl	String	否	图片URL
        OapiRobotSendRequest.Link link = new OapiRobotSendRequest.Link();
        link.setTitle(msg.getTitle());
        link.setText(msg.getText());
        link.setMessageUrl(msg.getMessageUrl());
        link.setPicUrl(msg.getPicUrl());

        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(MSG_TYPE_LINK);
        request.setLink(link);
        request.setAt(toAt(at));

        DingTalkRobotNotifyExecutor.Msg msg_ = new DingTalkRobotNotifyExecutor.Msg();
        msg_.setAccessToken(accessToken);
        msg_.setSignKey(signKey);
        msg_.setRequest(request);
        this.executor.write(msg_);
    }

    @Override
    public void sendMsg(DingTalkRobotMarkdownMsg msg) {
        this.sendMsg(msg, null);
    }

    @Override
    public void sendMsg(DingTalkRobotMarkdownMsg msg, MsgAt at) {
        //参数	类型	必选	说明
        //msgtype	String	是	此消息类型为固定markdown
        //title	String	是	首屏会话透出的展示内容
        //text	String	是	markdown格式的消息
        //atMobiles	Array	否	被@人的手机号(在text内容里要有@手机号)
        //isAtAll	bool	否	@所有人时：true，否则为：false
        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
        markdown.setTitle(msg.getTitle());
        markdown.setText(msg.getText());
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(MSG_TYPE_MARKDOWN);
        request.setMarkdown(markdown);
        request.setAt(toAt(at));

        DingTalkRobotNotifyExecutor.Msg msg_ = new DingTalkRobotNotifyExecutor.Msg();
        msg_.setAccessToken(accessToken);
        msg_.setSignKey(signKey);
        msg_.setRequest(request);
        this.executor.write(msg_);
    }

    @Override
    public void sendMsg(DingTalkRobotActionCardMsg msg) {
        this.sendMsg(msg, null);
    }

    @Override
    public void sendMsg(DingTalkRobotActionCardMsg msg, MsgAt at) {
        //参数	类型	必选	说明
        //    msgtype	string	true	此消息类型为固定actionCard
        //    title	string	true	首屏会话透出的展示内容
        //    text	string	true	markdown格式的消息
        //    singleTitle	string	true	单个按钮的方案。(设置此项和singleURL后btns无效)
        //    singleURL	string	true	点击singleTitle按钮触发的URL
        //    btnOrientation	string	false	0-按钮竖直排列，1-按钮横向排列
        //    hideAvatar	string	false	0-正常发消息者头像，1-隐藏发消息者头像
        OapiRobotSendRequest.Actioncard actionCard = new OapiRobotSendRequest.Actioncard();
        actionCard.setTitle(msg.getTitle());
        actionCard.setText(msg.getText());
        actionCard.setSingleTitle(msg.getSingleTitle());
        actionCard.setSingleURL(msg.getSingleURL());
        // 此处默认为0
        actionCard.setBtnOrientation(msg.getBtnOrientation() ? "1" : "0");
        // 此处默认为0
        actionCard.setHideAvatar(msg.getHideAvatar() ? "1" : "0");
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(MSG_TYPE_ACTION_CARD);
        request.setActionCard(actionCard);
        request.setAt(toAt(at));


        DingTalkRobotNotifyExecutor.Msg msg_ = new DingTalkRobotNotifyExecutor.Msg();
        msg_.setAccessToken(accessToken);
        msg_.setSignKey(signKey);
        msg_.setRequest(request);
        this.executor.write(msg_);
    }

    @Override
    public void sendMsg(DingTalkRobotFeedCardMsg msg) {
        this.sendMsg(msg, null);
    }

    @Override
    public void sendMsg(DingTalkRobotFeedCardMsg msg, MsgAt at) {
        //msgtype	string	true	此消息类型为固定feedCard
        //title	string	true	单条信息文本
        //messageURL	string	true	点击单条信息到跳转链接
        //picURL	string	true	单条信息后面图片的URL
        OapiRobotSendRequest.Feedcard feedcard = new OapiRobotSendRequest.Feedcard();
        List<OapiRobotSendRequest.Links> collect = msg.getLinks().stream()
                .map(item -> {
                    OapiRobotSendRequest.Links links = new OapiRobotSendRequest.Links();
                    links.setTitle(item.getTitle());
                    links.setMessageURL(item.getMessageURL());
                    links.setPicURL(item.getPicURL());
                    return links;
                }).collect(Collectors.toList());
        feedcard.setLinks(collect);
        OapiRobotSendRequest request = new OapiRobotSendRequest();
        request.setMsgtype(MSG_TYPE_FEED_CARD);
        request.setFeedCard(feedcard);
        request.setAt(toAt(at));

        DingTalkRobotNotifyExecutor.Msg msg_ = new DingTalkRobotNotifyExecutor.Msg();
        msg_.setAccessToken(accessToken);
        msg_.setSignKey(signKey);
        msg_.setRequest(request);
        this.executor.write(msg_);
    }

    private OapiRobotSendRequest.At toAt(MsgAt at_) {
        if (at_ == null) {
            return null;
        }

        //        if (!CollectionUtils.isEmpty(mobileList)) {
//            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//            at.setIsAtAll(isAtAll ? "true" : "false");
//            at.setAtMobiles(mobileList);
//            request.setAt(at);
//        }

        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
        at.setIsAtAll(at_.getIsAtAll());
        at.setAtMobiles(at_.getAtMobiles());
        at.setAtUserIds(at_.getAtUserIds());
        return at;
    }


//
//    /**
//     * @description: 独立跳转ActionCard类型 消息发送
//     * @param title 标题
//     * @param markdownText  文本
//     * @param btns  按钮列表
//     * @param btnOrientation    是否横向排列(true 横向排列, false 纵向排列)
//     * @param hideAvatar    是否隐藏发消息者头像(true 隐藏头像, false 不隐藏)
//     * @return: com.dingtalk.api.response.OapiRobotSendResponse
//     * @author: niaonao
//     * @date: 2019/7/6
//     */
//    public static OapiRobotSendResponse sendMessageByActionCardMulti(String title, String markdownText, List<OapiRobotSendRequest.Btns> btns, boolean btnOrientation, boolean hideAvatar) {
//        if (!DataValidUtil.checkNotEmpty(title, markdownText) || CollectionUtils.isEmpty(btns)) {
//            return null;
//        }
//        //参数	类型	必选	说明
//        //msgtype	string	true	此消息类型为固定actionCard
//        //title	string	true	首屏会话透出的展示内容
//        //text	string	true	markdown格式的消息
//        //btns	array	true	按钮的信息：title-按钮方案，actionURL-点击按钮触发的URL
//        //btnOrientation	string	false	0-按钮竖直排列，1-按钮横向排列
//        //hideAvatar	string	false	0-正常发消息者头像，1-隐藏发消息者头像
//        OapiRobotSendRequest.Actioncard actionCard = new OapiRobotSendRequest.Actioncard();
//        actionCard.setTitle(title);
//        actionCard.setText(markdownText);
//        // 此处默认为0
//        actionCard.setBtnOrientation(btnOrientation ? "1" : "0");
//        // 此处默认为0
//        actionCard.setHideAvatar(hideAvatar ? "1" : "0");
//
//        actionCard.setBtns(btns);
//
//        OapiRobotSendRequest request = new OapiRobotSendRequest();
//        request.setMsgtype(RobotHelperUtil.MSG_TYPE_ACTION_CARD);
//        request.setActionCard(actionCard);
//        OapiRobotSendResponse response = new OapiRobotSendResponse();
//        try {
//            response = RobotHelperUtil.client.execute(request);
//        } catch (ApiException e) {
//            log.error("[发送ActionCard 类型消息]: 独立跳转ActionCard类型发送消息失败, 异常捕获{}", e.getMessage());
//        }
//        return response;
//    }


//    public static void sdkDemoJava() {
//        DingTalkClient client = RobotHelperUtil.client;
//        OapiRobotSendRequest request = new OapiRobotSendRequest();
//        request.setMsgtype("text");
//        OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
//        text.setContent("测试文本消息");
//        request.setText(text);
//        OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
//        at.setAtMobiles(Arrays.asList("13261303345"));
//        request.setAt(at);
//
//        request.setMsgtype("link");
//        OapiRobotSendRequest.Link link = new OapiRobotSendRequest.Link();
//        link.setMessageUrl("https://www.dingtalk.com/");
//        link.setPicUrl("");
//        link.setTitle("时代的火车向前开");
//        link.setText("这个即将发布的新版本，创始人陈航（花名“无招”）称它为“红树林”。\n" +
//                "而在此之前，每当面临重大升级，产品经理们都会取一个应景的代号，这一次，为什么是“红树林");
//        request.setLink(link);
//
//        request.setMsgtype("markdown");
//        OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
//        markdown.setTitle("杭州天气");
//        markdown.setText("#### 杭州天气 @156xxxx8827\n" +
//                "> 9度，西北风1级，空气良89，相对温度73%\n\n" +
//                "> ![screenshot](https://gw.alipayobjects.com/zos/skylark-tools/public/files/84111bbeba74743d2771ed4f062d1f25.png)\n"  +
//                "> ###### 10点20分发布 [天气](http://www.thinkpage.cn/) \n");
//        request.setMarkdown(markdown);
//        try {
//            client.execute(request);
//        } catch (ApiException e) {
//            log.error("[ApiException]: 消息发送演示示例, 异常捕获{}", e.getMessage());
//        }
//    }

}
